package org.example.pet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.pet.common.expection.AuthenticationException;
import org.example.pet.common.expection.CustomException;
import org.example.pet.dto.UserDetailDTO;
import org.example.pet.dto.UserPageQueryDTO;
import org.example.pet.mapper.UserMapper;
import org.example.pet.pojo.Pet;
import org.example.pet.pojo.User;
import org.example.pet.service.UserService;
import org.example.pet.util.BCryptUtil;
import org.example.pet.util.JwtUtil;
import org.example.pet.util.RegexUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 用户注册逻辑
     * @param user 注册用户信息
     */
    @Override
    public void register(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();

        // 非空校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password) || !StringUtils.hasLength(email)) {
            throw new CustomException("用户名、密码、邮箱不能为空");
        }

        // 邮箱格式校验
        if (!RegexUtils.isEmailValid(email)) {
            throw new CustomException("邮箱格式不合法");
        }

        // 用户名查重
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        if (this.getOne(queryWrapper) != null) {
            throw new CustomException("用户名已被注册");
        }

        // 密码加密
        user.setPassword(BCryptUtil.encrypt(password));

        // 填充默认值
        user.setRole(User.RoleVal.USER.getVal()); // 默认普通用户
        user.setStatus(User.StatusVal.ACTIVE.getVal()); // 默认激活
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        // 保存用户信息
        boolean saveSuccess = this.save(user);
        if (!saveSuccess) {
            throw new CustomException("注册失败，请重试");
        }
    }

    /**
     * 用户登录逻辑
     * @param user 登录用户信息
     * @return 登录成功的用户信息
     */
    @Override
    public Map<String, Object> login(User user) {
        String username = user.getUsername();
        String password = user.getPassword();

        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            throw new CustomException("用户名或密码不能为空");
        }

        // 校验用户存在性
        User loginUser = userMapper.selectByUsername(username);

        if (loginUser == null) {
            throw new CustomException("用户名或密码错误");
        }

        // 校验密码
        if (!BCryptUtil.verify(user.getPassword(), loginUser.getPassword())) {
            throw new CustomException("用户名或密码错误");
        }

        // 校验用户可用性
        if (!User.StatusVal.ACTIVE.getVal().equals(loginUser.getStatus())) {
            throw new CustomException("账户已被禁用，请联系管理员");
        }
        
        String token = jwtUtil.generateToken(username, user.getRole());
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("username", username);
        result.put("role", loginUser.getRole());
        
        return result;
    }

    // 根据用户名查询用户
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public UserDetailDTO updateUserInfo(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();
        wrapper.eq(User::getUsername, user.getUsername());
        update(user, wrapper);
        
        UserDetailDTO userDetailDTO = new UserDetailDTO();
        BeanUtils.copyProperties(user,userDetailDTO);
        return userDetailDTO;
    }

    @Override
    public Page<User> page(UserPageQueryDTO queryDTO) {
        // 处理分页参数默认值
        int page = queryDTO.getPage() == null ? 1 : queryDTO.getPage();
        int pageSize = queryDTO.getPageSize() == null ? 7 : queryDTO.getPageSize();

        // 校验分页参数合法性
        page = Math.max(page, 1);
        pageSize = Math.max(pageSize, 1);
        pageSize = Math.min(pageSize, 100);

        // 构造分页构造器对象
        Page<User> pageInfo = new Page<>(page,pageSize);

        // 条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加过滤条件
        if(StringUtils.hasText(queryDTO.getRole())) {
            queryWrapper.like(User::getRole, queryDTO.getRole());
        }
        if(StringUtils.hasText(queryDTO.getUsername())) {
            queryWrapper.like(User::getUsername, queryDTO.getUsername());
        }
        
        // 添加排序条件
        queryWrapper.orderByDesc(User::getUpdatedAt);
        
        page(pageInfo,queryWrapper);
        
        return pageInfo;
    }
}
